<template>
  <div class="video-tools">
    <el-container>
      <el-main>
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>视频处理</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 主要功能区域 -->
        <el-card class="tool-container">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="格式转换" name="convert">
              <div class="tool-section">
                <el-upload
                  class="upload-area"
                  drag
                  action="#"
                  :auto-upload="false"
                  :on-change="handleVideoChange"
                  :show-file-list="false"
                  accept="video/*"
                >
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    拖拽视频到此处或 <em>点击上传</em>
                  </div>
                </el-upload>
                
                <div v-if="videoUrl" class="video-preview">
                  <video :src="videoUrl" controls></video>
                  <div class="video-info">
                    <p>文件名：{{ fileName }}</p>
                    <p>文件大小：{{ fileSize }}</p>
                    <p>时长：{{ duration }}</p>
                    <p>分辨率：{{ resolution }}</p>
                    <p>编码：{{ codec }}</p>
                  </div>
                </div>
                
                <div class="convert-options" v-if="videoUrl">
                  <div class="ffmpeg-status" style="margin-bottom: 20px; padding: 10px; border-radius: 4px;" :style="ffmpegStatusStyle">
                    <p><strong>FFmpeg 状态:</strong> {{ ffmpegStatusText }}</p>
                    <el-button size="small" @click="testFFmpeg" :disabled="!ffmpegLoaded">测试 FFmpeg</el-button>
                  </div>
                  
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-select v-model="targetFormat" placeholder="选择目标格式">
                        <el-option label="MP4 (H.264)" value="mp4" />
                        <el-option label="WebM (VP9)" value="webm" />
                        <el-option label="AVI (H.264)" value="avi" />
                        <el-option label="MOV (H.264)" value="mov" />
                        <el-option label="MKV (H.264)" value="mkv" />
                        <el-option label="FLV (H.264)" value="flv" />
                      </el-select>
                    </el-col>
                    <el-col :span="12">
                      <el-select v-model="videoCodec" placeholder="选择视频编码">
                        <el-option label="H.264 (推荐)" value="libx264" />
                        <el-option label="H.265 (HEVC)" value="libx265" />
                        <el-option label="VP9" value="libvpx-vp9" />
                        <el-option label="AV1" value="libaom-av1" />
                      </el-select>
                    </el-col>
                  </el-row>
                  
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-select v-model="quality" placeholder="选择视频质量">
                        <el-option label="最高质量 (CRF 18)" value="18" />
                        <el-option label="高质量 (CRF 23)" value="23" />
                        <el-option label="中等质量 (CRF 28)" value="28" />
                        <el-option label="低质量 (CRF 35)" value="35" />
                        <el-option label="自定义比特率" value="custom" />
                      </el-select>
                    </el-col>
                    <el-col :span="12" v-if="quality === 'custom'">
                      <el-input v-model="customBitrate" placeholder="比特率 (kbps)">
                        <template #append>kbps</template>
                      </el-input>
                    </el-col>
                  </el-row>
                  
                  <div class="button-group">
                    <el-button type="primary" @click="handleConvert" :loading="loading" :disabled="!ffmpegLoaded">
                      转换
                    </el-button>
                    <el-button type="success" @click="handleDownload" :disabled="!processedBlob">
                      下载
                    </el-button>
                  </div>
                  
                  <div v-if="progress > 0" class="progress-section">
                    <el-progress :percentage="progress" :status="progressStatus"></el-progress>
                    <p class="progress-text">{{ progressText }}</p>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="视频压缩" name="compress">
              <div class="tool-section">
                <el-upload
                  class="upload-area"
                  drag
                  action="#"
                  :auto-upload="false"
                  :on-change="handleVideoChange"
                  :show-file-list="false"
                  accept="video/*"
                >
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    拖拽视频到此处或 <em>点击上传</em>
                  </div>
                </el-upload>
                
                <div v-if="videoUrl" class="video-preview">
                  <video :src="videoUrl" controls></video>
                  <div class="video-info">
                    <p>文件名：{{ fileName }}</p>
                    <p>文件大小：{{ fileSize }}</p>
                    <p>时长：{{ duration }}</p>
                    <p>分辨率：{{ resolution }}</p>
                  </div>
                </div>
                
                <div class="compress-options" v-if="videoUrl">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <label>目标分辨率</label>
                      <el-select v-model="targetResolution" placeholder="选择分辨率">
                        <el-option label="保持原分辨率" value="original" />
                        <el-option label="4K (3840x2160)" value="4k" />
                        <el-option label="2K (2560x1440)" value="2k" />
                        <el-option label="1080p (1920x1080)" value="1080p" />
                        <el-option label="720p (1280x720)" value="720p" />
                        <el-option label="480p (854x480)" value="480p" />
                        <el-option label="360p (640x360)" value="360p" />
                      </el-select>
                    </el-col>
                    <el-col :span="12">
                      <label>压缩级别</label>
                      <el-slider
                        v-model="compressLevel"
                        :min="18"
                        :max="35"
                        :step="1"
                        show-input
                        :format-tooltip="formatCompressLevel"
                      />
                    </el-col>
                  </el-row>
                  
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <label>帧率 (FPS)</label>
                      <el-select v-model="targetFps" placeholder="选择帧率">
                        <el-option label="保持原帧率" value="original" />
                        <el-option label="60 FPS" value="60" />
                        <el-option label="30 FPS" value="30" />
                        <el-option label="24 FPS" value="24" />
                        <el-option label="15 FPS" value="15" />
                      </el-select>
                    </el-col>
                    <el-col :span="12">
                      <el-checkbox v-model="enableAudioCompression">音频压缩</el-checkbox>
                      <el-input v-if="enableAudioCompression" v-model="audioBitrate" placeholder="音频比特率">
                        <template #append>kbps</template>
                      </el-input>
                    </el-col>
                  </el-row>
                  
                  <div class="button-group">
                    <el-button type="primary" @click="handleCompress" :loading="loading" :disabled="!ffmpegLoaded">
                      压缩
                    </el-button>
                    <el-button type="success" @click="handleDownload" :disabled="!processedBlob">
                      下载
                    </el-button>
                  </div>
                  
                  <div v-if="progress > 0" class="progress-section">
                    <el-progress :percentage="progress" :status="progressStatus"></el-progress>
                    <p class="progress-text">{{ progressText }}</p>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="视频剪辑" name="trim">
              <div class="tool-section">
                <el-upload
                  class="upload-area"
                  drag
                  action="#"
                  :auto-upload="false"
                  :on-change="handleVideoChange"
                  :show-file-list="false"
                  accept="video/*"
                >
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    拖拽视频到此处或 <em>点击上传</em>
                  </div>
                </el-upload>
                
                <div v-if="videoUrl" class="video-preview">
                  <video :src="videoUrl" controls ref="videoRef"></video>
                  <div class="video-info">
                    <p>文件名：{{ fileName }}</p>
                    <p>文件大小：{{ fileSize }}</p>
                    <p>时长：{{ duration }}</p>
                  </div>
                </div>
                
                <div class="trim-options" v-if="videoUrl">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <label>开始时间 (秒)</label>
                      <el-input-number v-model="startTime" :min="0" :max="videoDuration" :step="0.1" />
                    </el-col>
                    <el-col :span="12">
                      <label>结束时间 (秒)</label>
                      <el-input-number v-model="endTime" :min="0" :max="videoDuration" :step="0.1" />
                    </el-col>
                  </el-row>
                  
                  <div class="time-slider">
                    <label>时间范围选择</label>
                    <el-slider
                      v-model="trimRange"
                      range
                      :min="0"
                      :max="videoDuration"
                      :step="0.1"
                      :format-tooltip="formatTime"
                      @change="updateTimeInputs"
                    />
                  </div>
                  
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-checkbox v-model="enableFadeIn">淡入效果</el-checkbox>
                      <el-input-number v-if="enableFadeIn" v-model="fadeInDuration" :min="0" :max="5" :step="0.1" placeholder="淡入时长(秒)" />
                    </el-col>
                    <el-col :span="12">
                      <el-checkbox v-model="enableFadeOut">淡出效果</el-checkbox>
                      <el-input-number v-if="enableFadeOut" v-model="fadeOutDuration" :min="0" :max="5" :step="0.1" placeholder="淡出时长(秒)" />
                    </el-col>
                  </el-row>
                  
                  <div class="button-group">
                    <el-button @click="previewTrim">预览片段</el-button>
                    <el-button type="primary" @click="handleTrim" :loading="loading" :disabled="!ffmpegLoaded">
                      剪辑
                    </el-button>
                    <el-button type="success" @click="handleDownload" :disabled="!processedBlob">
                      下载
                    </el-button>
                  </div>
                  
                  <div v-if="progress > 0" class="progress-section">
                    <el-progress :percentage="progress" :status="progressStatus"></el-progress>
                    <p class="progress-text">{{ progressText }}</p>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>

        <!-- 使用公共功能介绍组件 -->
        <FeatureIntro
          :title="featureConfig.title"
          :description="featureConfig.description"
          :header-icon="featureConfig.headerIcon"
          :features="featureConfig.features"
          :initial-visible="showIntro"
          @close="showIntro = false"
        />

      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, VideoPlay, Close, Switch, Download, Fold, Setting } from '@element-plus/icons-vue'
import { FFmpeg } from '@ffmpeg/ffmpeg'
import { fetchFile, toBlobURL } from '@ffmpeg/util'
import FeatureIntro from '@/components/FeatureIntro.vue'
import { featuresConfig } from '@/config/featuresConfig.js'

export default {
  name: 'VideoTools',
  components: {
    UploadFilled,
    VideoPlay,
    Close,
    Switch,
    Download,
    Fold,
    Setting,
    FeatureIntro
  },
  setup() {
    const activeTab = ref('convert')
    const loading = ref(false)
    const videoUrl = ref('')
    const fileName = ref('')
    const fileSize = ref('')
    const duration = ref('')
    const resolution = ref('')
    const codec = ref('')
    const videoDuration = ref(0)
    const currentFile = ref(null)
    const processedBlob = ref(null)
    const videoRef = ref(null)
    
    // FFmpeg 实例
    const ffmpeg = ref(null)
    const ffmpegLoaded = ref(false)
    
    // 进度相关
    const progress = ref(0)
    const progressStatus = ref('')
    const progressText = ref('')
    
    // 转换选项
    const targetFormat = ref('mp4')
    const videoCodec = ref('libx264')
    const quality = ref('23')
    const customBitrate = ref('2000')
    
    // 压缩选项
    const targetResolution = ref('original')
    const compressLevel = ref(23)
    const targetFps = ref('original')
    const enableAudioCompression = ref(false)
    const audioBitrate = ref('128')
    
    // 剪辑选项
    const trimRange = ref([0, 0])
    const startTime = ref(0)
    const endTime = ref(0)
    const enableFadeIn = ref(false)
    const enableFadeOut = ref(false)
    const fadeInDuration = ref(1)
    const fadeOutDuration = ref(1)

    const showIntro = ref(true)
    const featureConfig = featuresConfig.videoTools

    // FFmpeg 状态计算属性
    const ffmpegStatusText = computed(() => {
      if (!ffmpegLoaded.value) {
        return '⏳ 加载中...'
      }
      return '✅ 已加载 (本地)'
    })

    const ffmpegStatusStyle = computed(() => {
      if (!ffmpegLoaded.value) {
        return { background: '#f0f9ff' }
      }
      return { background: '#f0f9ff', border: '1px solid #67c23a' }
    })

    // 初始化 FFmpeg
    const initFFmpeg = async () => {
      try {
        ElMessage.info('正在加载 FFmpeg，请稍候...')
        console.log('开始初始化 FFmpeg')
        
        // 创建 FFmpeg 实例
        ffmpeg.value = new FFmpeg()
        console.log('FFmpeg 实例创建成功')
        
        // 使用本地文件加载 FFmpeg 核心文件
        console.log('使用本地文件加载 FFmpeg 核心文件...')
        
        await ffmpeg.value.load({
          coreURL: await toBlobURL('./src/common/ffmpeg/ffmpeg-core.js', 'text/javascript'),
          wasmURL: await toBlobURL('./src/common/ffmpeg/ffmpeg-core.wasm', 'application/wasm'),
        })
        
        console.log('FFmpeg 核心加载成功')
        ffmpegLoaded.value = true
        ElMessage.success('FFmpeg 加载完成，可以开始处理视频了！')
        
        // 设置进度监听
        try {
          ffmpeg.value.on('progress', ({ progress: p }) => {
            progress.value = Math.round(p * 100)
            progressText.value = `处理中... ${Math.round(p * 100)}%`
          })
          console.log('进度监听器设置成功')
        } catch (progressError) {
          console.log('进度监听器设置失败，将使用手动进度更新')
        }
        
      } catch (error) {
        console.error('FFmpeg 初始化失败:', error)
        ElMessage.error('FFmpeg 加载失败: ' + error.message)
        ffmpegLoaded.value = false
      }
    }

    // 测试 FFmpeg 功能
    const testFFmpeg = async () => {
      try {
        ElMessage.info('正在测试 FFmpeg...')
        console.log('开始 FFmpeg 功能测试')
        
        if (!ffmpegLoaded.value || !ffmpeg.value) {
          ElMessage.error('FFmpeg 未正确加载')
          return
        }
        
        // 测试基本命令
        await ffmpeg.value.exec(['-version'])
        console.log('FFmpeg 版本命令执行成功')
        
        ElMessage.success('FFmpeg 测试通过，功能正常')
      } catch (error) {
        console.error('FFmpeg 测试失败:', error)
        ElMessage.error('FFmpeg 测试失败: ' + error.message)
      }
    }

    onMounted(() => {
      initFFmpeg()
    })

    // 工具函数
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const formatTime = (seconds) => {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const remainingSeconds = Math.floor(seconds % 60)
      
      if (hours > 0) {
        return `${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      }
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    }

    const formatCompressLevel = (val) => {
      const quality = val <= 20 ? '最高' : val <= 25 ? '高' : val <= 30 ? '中等' : '低'
      return `CRF ${val} (${quality})`
    }

    // 文件处理
    const handleVideoChange = async (file) => {
      if (!file) return
      
      const isVideo = file.raw.type.startsWith('video/')
      if (!isVideo) {
        ElMessage.error('请上传视频文件')
        return
      }

      const reader = new FileReader()
      reader.onload = (e) => {
        videoUrl.value = e.target.result
        fileName.value = file.name
        fileSize.value = formatFileSize(file.raw.size)
        currentFile.value = file.raw
        
        const video = document.createElement('video')
        video.src = e.target.result
        video.onloadedmetadata = () => {
          videoDuration.value = video.duration
          duration.value = formatTime(video.duration)
          resolution.value = `${video.videoWidth}x${video.videoHeight}`
          trimRange.value = [0, video.duration]
          endTime.value = video.duration
          
          // 尝试获取编码信息
          extractVideoInfo(file.raw)
        }
      }
      reader.readAsDataURL(file.raw)
    }

    // 提取视频信息
    const extractVideoInfo = async (file) => {
      if (!ffmpegLoaded.value) return
      
      try {
        const inputName = 'input.' + file.name.split('.').pop()
        await ffmpeg.value.writeFile(inputName, await fetchFile(file))
        
        // 使用 ffprobe 获取详细信息
        await ffmpeg.value.exec(['-i', inputName, '-hide_banner'])
      } catch (error) {
        // FFmpeg 会输出到 stderr，这是正常的
        codec.value = '未知'
      }
    }

    // 视频转换
    const handleConvert = async () => {
      if (!ffmpegLoaded.value) {
        ElMessage.warning('FFmpeg 还未加载完成，请稍候')
        return
      }
      
      if (!currentFile.value) {
        ElMessage.warning('请先上传视频')
        return
      }
      
      loading.value = true
      progress.value = 0
      progressStatus.value = ''
      progressText.value = '开始转换...'
      
      try {
        const inputName = 'input.' + currentFile.value.name.split('.').pop()
        const outputName = `output.${targetFormat.value}`
        
        progress.value = 10
        progressText.value = '准备文件...'
        
        // 写入输入文件
        await ffmpeg.value.writeFile(inputName, await fetchFile(currentFile.value))
        
        progress.value = 30
        progressText.value = '构建转换命令...'
        
        // 构建 FFmpeg 命令
        const args = ['-i', inputName]
        
        // 视频编码
        args.push('-c:v', videoCodec.value)
        
        // 质量设置
        if (quality.value === 'custom') {
          args.push('-b:v', `${customBitrate.value}k`)
        } else {
          args.push('-crf', quality.value)
        }
        
        // 音频编码
        args.push('-c:a', 'aac')
        args.push('-b:a', '128k')
        
        // 输出文件
        args.push(outputName)
        
        progress.value = 50
        progressText.value = '开始转换...'
        
        // 执行转换
        await ffmpeg.value.exec(args)
        
        progress.value = 90
        progressText.value = '读取结果...'
        
        // 读取输出文件
        const data = await ffmpeg.value.readFile(outputName)
        const blob = new Blob([data.buffer], { type: `video/${targetFormat.value}` })
        
        processedBlob.value = blob
        
        // 更新预览
        const convertedUrl = URL.createObjectURL(blob)
        videoUrl.value = convertedUrl
        fileSize.value = formatFileSize(blob.size)
        
        progress.value = 100
        progressStatus.value = 'success'
        progressText.value = '转换完成'
        
        ElMessage.success('视频转换完成')
      } catch (error) {
        console.error('转换失败:', error)
        progress.value = 0
        progressStatus.value = 'exception'
        progressText.value = '转换失败'
        ElMessage.error('转换失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 视频压缩
    const handleCompress = async () => {
      if (!ffmpegLoaded.value) {
        ElMessage.warning('FFmpeg 还未加载完成，请稍候')
        return
      }
      
      if (!currentFile.value) {
        ElMessage.warning('请先上传视频')
        return
      }
      
      loading.value = true
      progress.value = 0
      progressStatus.value = ''
      progressText.value = '开始压缩...'
      
      try {
        const inputName = 'input.' + currentFile.value.name.split('.').pop()
        const outputName = 'compressed.mp4'
        
        progress.value = 10
        progressText.value = '准备文件...'
        
        await ffmpeg.value.writeFile(inputName, await fetchFile(currentFile.value))
        
        progress.value = 30
        progressText.value = '构建压缩命令...'
        
        const args = ['-i', inputName]
        
        // 视频编码和质量
        args.push('-c:v', 'libx264')
        args.push('-crf', compressLevel.value.toString())
        
        // 分辨率设置
        if (targetResolution.value !== 'original') {
          const resolutions = {
            '4k': '3840:2160',
            '2k': '2560:1440',
            '1080p': '1920:1080',
            '720p': '1280:720',
            '480p': '854:480',
            '360p': '640:360'
          }
          args.push('-vf', `scale=${resolutions[targetResolution.value]}`)
        }
        
        // 帧率设置
        if (targetFps.value !== 'original') {
          args.push('-r', targetFps.value)
        }
        
        // 音频设置
        if (enableAudioCompression.value) {
          args.push('-c:a', 'aac')
          args.push('-b:a', `${audioBitrate.value}k`)
        } else {
          args.push('-c:a', 'copy')
        }
        
        args.push(outputName)
        
        progress.value = 50
        progressText.value = '开始压缩...'
        
        await ffmpeg.value.exec(args)
        
        progress.value = 90
        progressText.value = '读取结果...'
        
        const data = await ffmpeg.value.readFile(outputName)
        const blob = new Blob([data.buffer], { type: 'video/mp4' })
        
        processedBlob.value = blob
        
        const compressedUrl = URL.createObjectURL(blob)
        videoUrl.value = compressedUrl
        fileSize.value = formatFileSize(blob.size)
        
        progress.value = 100
        progressStatus.value = 'success'
        progressText.value = '压缩完成'
        
        ElMessage.success('视频压缩完成')
      } catch (error) {
        console.error('压缩失败:', error)
        progress.value = 0
        progressStatus.value = 'exception'
        progressText.value = '压缩失败'
        ElMessage.error('压缩失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 视频剪辑
    const handleTrim = async () => {
      if (!ffmpegLoaded.value) {
        ElMessage.warning('FFmpeg 还未加载完成，请稍候')
        return
      }
      
      if (!currentFile.value) {
        ElMessage.warning('请先上传视频')
        return
      }
      
      if (startTime.value >= endTime.value) {
        ElMessage.warning('开始时间必须小于结束时间')
        return
      }
      
      loading.value = true
      progress.value = 0
      progressStatus.value = ''
      progressText.value = '开始剪辑...'
      
      try {
        const inputName = 'input.' + currentFile.value.name.split('.').pop()
        const outputName = 'trimmed.mp4'
        
        progress.value = 10
        progressText.value = '准备文件...'
        
        await ffmpeg.value.writeFile(inputName, await fetchFile(currentFile.value))
        
        progress.value = 30
        progressText.value = '构建剪辑命令...'
        
        const args = ['-i', inputName]
        
        // 设置开始时间和持续时间
        args.push('-ss', startTime.value.toString())
        args.push('-t', (endTime.value - startTime.value).toString())
        
        // 视频编码
        args.push('-c:v', 'libx264')
        args.push('-c:a', 'aac')
        
        // 添加淡入淡出效果
        const filters = []
        if (enableFadeIn.value) {
          filters.push(`fade=in:0:${Math.round(fadeInDuration.value * 30)}`)
        }
        if (enableFadeOut.value) {
          const duration = endTime.value - startTime.value
          const fadeStart = Math.max(0, duration - fadeOutDuration.value)
          filters.push(`fade=out:${Math.round(fadeStart * 30)}:${Math.round(fadeOutDuration.value * 30)}`)
        }
        
        if (filters.length > 0) {
          args.push('-vf', filters.join(','))
        }
        
        args.push(outputName)
        
        progress.value = 50
        progressText.value = '开始剪辑...'
        
        await ffmpeg.value.exec(args)
        
        progress.value = 90
        progressText.value = '读取结果...'
        
        const data = await ffmpeg.value.readFile(outputName)
        const blob = new Blob([data.buffer], { type: 'video/mp4' })
        
        processedBlob.value = blob
        
        const trimmedUrl = URL.createObjectURL(blob)
        videoUrl.value = trimmedUrl
        fileSize.value = formatFileSize(blob.size)
        duration.value = formatTime(endTime.value - startTime.value)
        
        progress.value = 100
        progressStatus.value = 'success'
        progressText.value = '剪辑完成'
        
        ElMessage.success('视频剪辑完成')
      } catch (error) {
        console.error('剪辑失败:', error)
        progress.value = 0
        progressStatus.value = 'exception'
        progressText.value = '剪辑失败'
        ElMessage.error('剪辑失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 预览剪辑片段
    const previewTrim = () => {
      if (videoRef.value) {
        videoRef.value.currentTime = startTime.value
        videoRef.value.play()
        
        setTimeout(() => {
          videoRef.value.pause()
        }, (endTime.value - startTime.value) * 1000)
      }
    }

    // 更新时间输入
    const updateTimeInputs = (range) => {
      startTime.value = range[0]
      endTime.value = range[1]
    }

    // 监听时间输入变化
    watch([startTime, endTime], ([start, end]) => {
      trimRange.value = [start, end]
    })

    // 下载处理后的视频
    const handleDownload = () => {
      if (!processedBlob.value) {
        ElMessage.warning('请先处理视频')
        return
      }
      
      const url = URL.createObjectURL(processedBlob.value)
      const a = document.createElement('a')
      a.href = url
      
      let extension = 'mp4'
      if (activeTab.value === 'convert') {
        extension = targetFormat.value
      }
      
      a.download = `processed_${fileName.value.split('.')[0]}.${extension}`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      ElMessage.success('下载成功')
    }

    return {
      activeTab,
      loading,
      videoUrl,
      fileName,
      fileSize,
      duration,
      resolution,
      codec,
      videoDuration,
      videoRef,
      ffmpegLoaded,
      progress,
      progressStatus,
      progressText,
      targetFormat,
      videoCodec,
      quality,
      customBitrate,
      targetResolution,
      compressLevel,
      targetFps,
      enableAudioCompression,
      audioBitrate,
      trimRange,
      startTime,
      endTime,
      enableFadeIn,
      enableFadeOut,
      fadeInDuration,
      fadeOutDuration,
      processedBlob,
      showIntro,
      formatTime,
      formatCompressLevel,
      handleVideoChange,
      handleConvert,
      handleCompress,
      handleTrim,
      handleDownload,
      previewTrim,
      updateTimeInputs,
      testFFmpeg,
      ffmpegStatusText,
      ffmpegStatusStyle,
      featureConfig
    }
  }
}
</script>

<style scoped>
.video-tools {
  min-height: 100vh;
  width: 100vw;
  background: none;
  margin: 0;
  padding: 0;
}

.el-main {
  padding: 20px 40px;
  background-color: #f5f7fa;
}

.tool-container {
  max-width: 1000px;
  margin: 0 auto;
}

.tool-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.upload-area {
  width: 100%;
}

.video-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.video-preview video {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.video-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 10px;
  text-align: center;
  color: #606266;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  width: 100%;
}

.video-info p {
  margin: 0;
  padding: 5px;
  background: white;
  border-radius: 4px;
}

.convert-options,
.compress-options,
.trim-options {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.time-slider {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.time-slider label {
  font-weight: 500;
  color: #303133;
}

.button-group {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  justify-content: center;
}

.progress-section {
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.progress-text {
  text-align: center;
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #303133;
}

.el-input-number {
  width: 100%;
}

@media (max-width: 768px) {
  .el-main {
    padding: 15px 20px;
  }
  
  .button-group {
    flex-direction: column;
  }
  
  .el-button {
    width: 100%;
  }
  
  .video-info {
    grid-template-columns: 1fr;
  }
}

/* 功能介绍卡片样式 */
.intro-card {
  max-width: 1000px;
  margin: 30px auto 0 auto;
  background: #fafbfc;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.intro-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.intro-header .el-icon {
  font-size: 18px;
  color: #909399;
}

.close-btn {
  margin-left: auto;
  color: #909399 !important;
}

.close-btn:hover {
  background-color: rgba(144, 147, 153, 0.1) !important;
  color: #606266 !important;
}

.intro-content {
  padding: 0;
}

.intro-description {
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 20px;
  color: #606266;
  text-align: center;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.feature-item {
  background: white;
  padding: 16px;
  border-radius: 6px;
  text-align: center;
  border: 1px solid #e4e7ed;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.feature-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.feature-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.feature-item h4 {
  margin: 0 0 6px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.feature-item p {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
  color: #909399;
}
</style> 